#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2025/3/27 23:13
@Author  : HZP
@File    : app_hander.py

"""
import uuid
from dataclasses import dataclass

from dotenv import load_dotenv
from flask import request
from injector import inject
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

from config import Config
from internal.schema.app_schema import CompletionReq
from internal.service import AppService
from internal.service.base_service import BaseService
from pkg.response.response import json_success


@inject
@dataclass
class AppHandler(BaseService):
    app_service: AppService
    config: Config

    def create_app(self):
        """创建一条数据"""
        app = self.app_service.create_app()
        print(app)
        return json_success()

    def update_app(self, app_id: uuid.UUID):
        """更新一条数据"""
        app = self.app_service.get_app(app_id)
        self.app_service.update_app(app)
        return json_success()

    def get_app(self, app_id: uuid.UUID):
        """获取一条数据"""
        app = self.app_service.get_app(app_id)
        return json_success()

    def delete_app(self, app_id: uuid.UUID):
        """删除一条数据"""
        self.app_service.delete_app(app_id)
        return json_success()

    def ping(self):
        """生成回复"""
        req = CompletionReq()
        if not req.validate():
            return {"error": req.errors}

        query = request.json.get("query")
        load_dotenv()

        llm = ChatOpenAI(model=self.config.LLM_MODEL_NAME, temperature=0.6)
        parse = StrOutputParser()
        prompt = ChatPromptTemplate.from_template("请回答一下问题:{query}")

        invoke = prompt | llm | parse
        content = invoke.invoke({"query": query})

        return json_success({"content": content})
